<template>
  <div class="customer-analysis">
    <el-page-header title="客户分析">
      <template #content>
        <span class="page-header-content">客户统计分析</span>
      </template>
    </el-page-header>

    <div class="analysis-content">
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="data-overview">
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>总客户数</span>
                <el-tag type="success">本月</el-tag>
              </div>
            </template>
            <div class="card-body">
              <div class="number">{{ statistics.totalCustomers }}</div>
              <div class="trend">
                <span :class="{ 'up': statistics.customerGrowth > 0, 'down': statistics.customerGrowth < 0 }">
                  {{ Math.abs(statistics.customerGrowth) }}%
                </span>
                较上月
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>新增客户</span>
                <el-tag type="warning">本月</el-tag>
              </div>
            </template>
            <div class="card-body">
              <div class="number">{{ statistics.newCustomers }}</div>
              <div class="trend">
                <span :class="{ 'up': statistics.newCustomerGrowth > 0, 'down': statistics.newCustomerGrowth < 0 }">
                  {{ Math.abs(statistics.newCustomerGrowth) }}%
                </span>
                较上月
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>贷款客户</span>
                <el-tag type="primary">本月</el-tag>
              </div>
            </template>
            <div class="card-body">
              <div class="number">{{ statistics.loanCustomers }}</div>
              <div class="trend">
                <span :class="{ 'up': statistics.loanCustomerGrowth > 0, 'down': statistics.loanCustomerGrowth < 0 }">
                  {{ Math.abs(statistics.loanCustomerGrowth) }}%
                </span>
                较上月
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>活跃客户</span>
                <el-tag type="info">本月</el-tag>
              </div>
            </template>
            <div class="card-body">
              <div class="number">{{ statistics.activeCustomers }}</div>
              <div class="trend">
                <span :class="{ 'up': statistics.activeCustomerGrowth > 0, 'down': statistics.activeCustomerGrowth < 0 }">
                  {{ Math.abs(statistics.activeCustomerGrowth) }}%
                </span>
                较上月
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-area">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <h3>客户增长趋势</h3>
                <el-radio-group v-model="customerTrendPeriod" size="small">
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="quarter">季</el-radio-button>
                  <el-radio-button label="year">年</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="customerTrendChart"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <h3>客户类型分布</h3>
                <el-select v-model="customerTypeFilter" size="small" style="width: 120px">
                  <el-option label="全部" value="all" />
                  <el-option label="新客户" value="new" />
                  <el-option label="老客户" value="old" />
                </el-select>
              </div>
            </template>
            <div class="chart-container" ref="customerTypeChart"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-area">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <h3>信用等级分布</h3>
              </div>
            </template>
            <div class="chart-container" ref="creditRatingChart"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <h3>客户来源分析</h3>
              </div>
            </template>
            <div class="chart-container" ref="customerSourceChart"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <h3>客户数据明细</h3>
            <div class="header-actions">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
              />
              <el-button type="primary" size="small" @click="exportData">导出数据</el-button>
            </div>
          </div>
        </template>

        <el-table :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="newCustomers" label="新增客户" width="120" />
          <el-table-column prop="totalCustomers" label="总客户数" width="120" />
          <el-table-column prop="loanCustomers" label="贷款客户" width="120" />
          <el-table-column prop="activeCustomers" label="活跃客户" width="120" />
          <el-table-column prop="avgLoanAmount" label="平均贷款金额">
            <template #default="scope">
              {{ formatMoney(scope.row.avgLoanAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="conversionRate" label="转化率">
            <template #default="scope">
              {{ scope.row.conversionRate }}%
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

export default {
  name: 'CustomerAnalysis',
  setup() {
    // 图表实例
    let customerTrendChartInstance = null
    let customerTypeChartInstance = null
    let creditRatingChartInstance = null
    let customerSourceChartInstance = null

    // 统计数据
    const statistics = reactive({
      totalCustomers: 1234,
      customerGrowth: 15.6,
      newCustomers: 89,
      newCustomerGrowth: -5.2,
      loanCustomers: 456,
      loanCustomerGrowth: 8.3,
      activeCustomers: 789,
      activeCustomerGrowth: 12.5
    })

    // 筛选条件
    const customerTrendPeriod = ref('month')
    const customerTypeFilter = ref('all')
    const dateRange = ref([])

    // 表格数据
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(100)
    const tableData = ref([
      {
        date: '2024-03-01',
        newCustomers: 30,
        totalCustomers: 1234,
        loanCustomers: 456,
        activeCustomers: 789,
        avgLoanAmount: 50000,
        conversionRate: 35.6
      }
    ])

    // 初始化图表
    const initCharts = () => {
      // 客户增长趋势图
      customerTrendChartInstance = echarts.init(document.querySelector('#customerTrendChart'))
      customerTrendChartInstance.setOption({
        title: {
          text: '客户增长趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['总客户数', '新增客户', '贷款客户']
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '总客户数',
            type: 'line',
            data: [1000, 1100, 1200, 1250, 1300, 1400]
          },
          {
            name: '新增客户',
            type: 'line',
            data: [100, 120, 90, 80, 70, 110]
          },
          {
            name: '贷款客户',
            type: 'line',
            data: [400, 420, 450, 460, 480, 500]
          }
        ]
      })

      // 客户类型分布图
      customerTypeChartInstance = echarts.init(document.querySelector('#customerTypeChart'))
      customerTypeChartInstance.setOption({
        title: {
          text: '客户类型分布'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: [
              { value: 735, name: '个人客户' },
              { value: 499, name: '企业客户' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })

      // 信用等级分布图
      creditRatingChartInstance = echarts.init(document.querySelector('#creditRatingChart'))
      creditRatingChartInstance.setOption({
        title: {
          text: '信用等级分布'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['A', 'B', 'C', 'D']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            type: 'bar',
            data: [
              { value: 400, itemStyle: { color: '#67C23A' } },
              { value: 500, itemStyle: { color: '#E6A23C' } },
              { value: 200, itemStyle: { color: '#909399' } },
              { value: 100, itemStyle: { color: '#F56C6C' } }
            ]
          }
        ]
      })

      // 客户来源分析图
      customerSourceChartInstance = echarts.init(document.querySelector('#customerSourceChart'))
      customerSourceChartInstance.setOption({
        title: {
          text: '客户来源分析'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 300, name: '主动申请' },
              { value: 200, name: '客户推荐' },
              { value: 150, name: '营销活动' },
              { value: 100, name: '合作渠道' },
              { value: 50, name: '其他' }
            ]
          }
        ]
      })
    }

    // 处理窗口大小变化
    const handleResize = () => {
      customerTrendChartInstance?.resize()
      customerTypeChartInstance?.resize()
      creditRatingChartInstance?.resize()
      customerSourceChartInstance?.resize()
    }

    // 导出数据
    const exportData = () => {
      ElMessage.success('数据导出成功')
    }

    // 格式化金额
    const formatMoney = (value) => {
      return `¥ ${value.toFixed(2)}`
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      // TODO: 重新加载数据
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      // TODO: 重新加载数据
    }

    onMounted(() => {
      initCharts()
      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      customerTrendChartInstance?.dispose()
      customerTypeChartInstance?.dispose()
      creditRatingChartInstance?.dispose()
      customerSourceChartInstance?.dispose()
    })

    return {
      statistics,
      customerTrendPeriod,
      customerTypeFilter,
      dateRange,
      loading,
      currentPage,
      pageSize,
      total,
      tableData,
      exportData,
      formatMoney,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.customer-analysis {
  padding: 20px;
}

.page-header-content {
  font-size: 20px;
  font-weight: bold;
}

.analysis-content {
  margin-top: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-body {
    text-align: center;

    .number {
      font-size: 24px;
      font-weight: bold;
      margin: 10px 0;
    }

    .trend {
      color: #666;
      font-size: 14px;

      span {
        margin-right: 5px;

        &.up {
          color: #67C23A;
        }

        &.down {
          color: #F56C6C;
        }
      }
    }
  }
}

.chart-area {
  margin-bottom: 20px;
}

.chart-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #409EFF;
    }
  }
}

.chart-container {
  height: 300px;
}

.table-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #409EFF;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 